package com.zkq.graduate.service.impl;

import com.zkq.graduate.enums.DateTimeFormatterEnum;
import com.zkq.graduate.mapper.TitleMapper;
import com.zkq.graduate.pojo.*;
import com.zkq.graduate.service.MajorService;
import com.zkq.graduate.service.TitleService;
import com.zkq.graduate.util.LocalDateTimeUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @Author zhangkaiqiang
 * @Date 2019/11/25  14:51
 * @Description TODO
 */
@Service(value = "titleService")
public class TitleServiceImpl implements TitleService {


	@Autowired
	TitleMapper titleMapper;

	@Autowired
	MajorService majorService;

	@Override
	public List<Title> listTitleByTeacherId(String teacherId) {
		List<Title> list=titleMapper.listTitleByTeacherId(teacherId);
		if(CollectionUtils.isEmpty(list)){
			return new ArrayList<>();
		}
		return list;
	}

	@Override
	public List<Title> listTitleByStudent(Student student) {
		List<Title> list=titleMapper.listTitleByStudent(student);
		if(CollectionUtils.isEmpty(list)){
			return new ArrayList<>();
		}
		return list;
	}

	@Override
	public boolean insertOneTitle(Title title) {
		// 根据专业的名称查找到专业的id和专业所属学院的id
		Optional<Major> major=majorService.findByName(title.getMajor().getMajorName());
		if(!major.isPresent()){
			return false;
		}
		major.ifPresent((item)->{
			title.setMajor(item);
			// 创建时间为当前时间
			String releaseTime=LocalDateTimeUtil.formatLocalDateTime(LocalDateTime.now(), DateTimeFormatterEnum.YEAR_MONTH_DAY);
			title.setReleaseTime(releaseTime);
			title.setUpdateTime(releaseTime);
		});
		return titleMapper.insertOneTitle(title)==1;
	}

	@Override
	public boolean delTitles(String[] titleIds) {
		return titleMapper.delTitles(titleIds)==titleIds.length;
	}

	@Override
	public boolean editTitle(Title title) {
		// 根据专业的名称查找到专业的id和专业所属学院的id
		Optional<Major> major=majorService.findByName(title.getMajor().getMajorName());
		if(!major.isPresent()){
			return false;
		}
		major.ifPresent((item)->{
			title.setMajor(item);
			String updateTime=LocalDateTimeUtil.formatLocalDateTime(LocalDateTime.now(), DateTimeFormatterEnum.YEAR_MONTH_DAY);
			title.setUpdateTime(updateTime);
		});
		return titleMapper.editTitle(title)==1;
	}

	@Override
	public Optional<Title> getTitleById(String id) {
		return Optional.ofNullable(titleMapper.getTitleById(id));
	}

	@Override
	public boolean updateSelectCount(Title title) {
		return titleMapper.editTitle(title)==1;
	}
}
